# -*- coding: utf-8 -*-

import sys
from io import BytesIO
from PySide import QtGui,QtCore
import scipy as spy
import pyqtgraph as pg
from .EQSignal_UI_D import Ui_EQSignal_
from .About_D import Ui_About_
from .EQSignal import EQSignal
from copy import deepcopy

class AutoPen(object):
    colors = ["b", "g", "r", "c", "m", "y"]
    n = 6
    i = -1
    color = "b"
    pen = pg.mkPen(color, width=2)

    def __iter__(self):
        return self

    def next(self):
        self.i += 1
        if self.i > self.n-1:
            self.i = 0
        self.color = self.colors[self.i]
        self.pen = pg.mkPen(self.color, width=2)
        return self.pen

    def reset(self):
        self.i = -1

# class EQTableModel(QtCore.QAbstractTableModel):
#     """docstring for EQTableModel"""
#     def __init__(self, parent, Data, Header):
#         super(EQTableModel, self).__init__(parent)
#         self.Data = Data
#         self.Header = Header

#     def rowCount(self, parent):
#         return spy.size(self.Data,0)

#     def columnCount(self, parent):
#         return spy.size(self.Data,1)

#     def data(self, index, role=QtCore.Qt.DisplayRole):
#         return self.Data[index.row(),index.column()]

#     def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
#         if orientation == QtCore.Qt.Horizontal:
#             return self.Header[section]
#         return None

# class EQTableWidget(QtGui.QTableWidget):
#     """docstring for EQTableWidget"""
#     def __init__(self, Data, parent=None):
#         rows, columns = spy.size(Data,0), spy.size(Data,1)
#         super(EQTableWidget, self).__init__(rows, columns, parent=parent)
#         self.setSelectionBehavior(QtGui.QAbstractItemView.SelectColumns)
#         # self.resize(400, 800)
        
#     def setHeader(self,Header):
#         for i in xrange(self.columnCount()):
#             self.setHorizontalHeaderItem(i, QtGui.QTableWidgetItem(Header[i]))

#     def setData(self,Data):
#         rows, columns = spy.size(Data,0), spy.size(Data,1)
#         self.setRowCount(rows)
#         self.setColumnCount(columns)
        
#         for i in xrange(rows):
#             for j in xrange(columns):
#                 self.setItem(i,j,QtGui.QTableWidgetItem(str(Data[i,j])))
#                 print(Data[i,j])

#     def keyPressEvent(self, e):
#         if (e.modifiers() & QtCore.Qt.ControlModifier):
#             selected = self.selectedRanges()

#             if e.key() == QtCore.Qt.Key_C: #copy
#                 s = ""

#                 for r in xrange(selected[0].topRow(), selected[0].bottomRow()+1):
#                     for c in xrange(selected[0].leftColumn(), selected[0].rightColumn()+1):
#                         try:
#                             s += str(self.item(r,c).text()) + "\t"
#                         except AttributeError:
#                             s += "\t"
#                     s = s[:-1] + "\n" #eliminate last '\t'
#                 QtGui.QApplication.clipboard().setText(s)

class Ui_About(QtGui.QWidget,Ui_About_):
    """docstring for Ui_ABOUT"""
    def __init__(self, parent=None):
        super(Ui_About, self).__init__(parent)
        self.setupUi(self)

class Ui_EQSignal(QtGui.QMainWindow, Ui_EQSignal_):

    """Ui_EQSignal"""

    def __init__(self, parent=None):
        super(Ui_EQSignal, self).__init__(parent)
        self.setupUi(self)
        self.eqs = EQSignal()
        self.initViewTH()
        self.initViewSPA()
        self.initViewSP()
        self.initViewFFT()
        # self.initTable()
        self.initTextEdit()
        self.fileName = ""
        self.about = Ui_About()

        self.setupConnection()

    def setupConnection(self):

        self.actionNGA_Record.triggered.connect(self.readNGAthenPlotTH)
        self.actionPlain_Text.triggered.connect(self.readTXTthenPlotTH)
        self.actionExcel.triggered.connect(self.eqs.save_xlsx)
        self.actionAbout.triggered.connect(self.about.show)

        self.ApplyAdjust.clicked.connect(self.adjustthenPlotTH)
        self.UndoAdjust.clicked.connect(self.resetthenPlotTH)
        self.RSPA.clicked.connect(self.calSPthenPlotSP)
        self.ViewASP.clicked.connect(self.calASPthenPlotASP)
        self.RawON.stateChanged.connect(self.plotTH)

        self.OPEN.clicked.connect(self.openFile)
        self.Reload.clicked.connect(self.reloadFile)
        self.Norm.clicked.connect(self.NormthenPlotTH)
        self.RecoverN.clicked.connect(self.recoverthenPlotTH)
        self.Refresh.clicked.connect(self.plotTH)
        self.RePlotTH.clicked.connect(self.plotTH)

        self.RePlotSPA.clicked.connect(self.plotCurrentSPA)

        self.setTB.clicked.connect(self.getTrimIndice)
        self.DoTrim.clicked.connect(self.trimthenPlotTH)
        self.Recover.clicked.connect(self.recoverthenPlotTH)

        self.X_LIN_FFT.clicked.connect(self.changeXS_FFT)
        self.X_LOG_FFT.clicked.connect(self.changeXS_FFT)
        self.X_LIN_SPA.clicked.connect(self.changeXS_SPA)
        self.X_LOG_SPA.clicked.connect(self.changeXS_SPA)
        self.X_LIN_SP.clicked.connect(self.changeXS_SP)
        self.X_LOG_SP.clicked.connect(self.changeXS_SP)

        self.SPfit.clicked.connect(self.fitSpectra)
        self.VDTH.clicked.connect(self.viewDataTH)
        self.VDSP.clicked.connect(self.viewDataSP)
        self.CDR.activated.connect(self.viewDataSPA)
        self.CDR2.activated.connect(self.viewDataSP)
        self.FSP.activated.connect(self.FFTPSD)
        self.DR.textChanged.connect(self.updateCDR)

        self.SPATON.stateChanged.connect(self.plotSPA)

    def initTextEdit(self):
        self.textEditSPA = QtGui.QTextBrowser()
        self.textEditSPA.resize(400,600)
        self.textEditSPA.setWindowTitle("Absolute Acceleration Spectrum")
        self.textEditTH = QtGui.QTextBrowser()
        self.textEditTH.resize(600,800)
        self.textEditTH.setWindowTitle("Time History")

    def initViewTH(self):
        accPlot = self.ViewTH.addPlot(0,0,title="Acceleration")
        accPlot.showGrid(x=True, y=True)
        accPlot.enableAutoRange()
        # accPlot.addLegend()
        # accPlot.legend.close()
        # accPlot.setLabels(bottom="time (s)")
        velPlot = self.ViewTH.addPlot(1,0,title="Velocity")
        velPlot.showGrid(x=True, y=True)
        velPlot.enableAutoRange()
        # velPlot.addLegend()
        # velPlot.legend.close()
        # velPlot.setLabels(bottom="time (s)")
        dispPlot = self.ViewTH.addPlot(2,0,title="Displacement")
        dispPlot.showGrid(x=True, y=True)
        dispPlot.enableAutoRange()
        # dispPlot.addLegend()
        # dispPlot.legend.close()
        dispPlot.setLabels(bottom="time (s)")

    def initViewFFT(self):

        fftPlot = self.ViewFFT.addPlot(0,0,title="Fourier Amplitude Spectrum")
        # fftPlot.setLogMode(x=True)
        fftPlot.showGrid(x=True, y=True)
        fftPlot.setLabels(left="Fourier Amplitude",bottom="Frequency (Hz)")
        fftPlot.enableAutoRange()

    def initViewSPA(self):

        spPlot = self.ViewSPA.addPlot(0,0,title="Acceleration Spectra")
        spPlot.setLogMode(x=True)
        spPlot.showGrid(x=True, y=True)
        spPlot.addLegend()
        spPlot.legend.close()
        spPlot.enableAutoRange()
        spPlot.setLabels(left="Response Acceleration",bottom="Period (s)")

    def initViewSP(self):
        spPlot = self.ViewSP.addPlot(0,0,title="Acceleration Spectra")
        spPlot.setLogMode(x=True)
        spPlot.showGrid(x=True, y=True)
        spPlot.addLegend()
        spPlot.legend.close()
        spPlot.enableAutoRange()

        spPlot = self.ViewSP.addPlot(0,1,title="Velocity Spectra")
        spPlot.setLogMode(x=True)
        spPlot.showGrid(x=True, y=True)
        spPlot.addLegend()
        spPlot.legend.close()
        spPlot.enableAutoRange()

        spPlot = self.ViewSP.addPlot(1,0,title="Displacement Spectra")
        spPlot.setLogMode(x=True)
        spPlot.showGrid(x=True, y=True)
        spPlot.addLegend()
        spPlot.legend.close()
        spPlot.enableAutoRange()

        spPlot = self.ViewSP.addPlot(1,1,title="Input Energy Spectra")
        spPlot.setLogMode(x=True)
        spPlot.showGrid(x=True, y=True)
        spPlot.addLegend()
        spPlot.legend.close()
        spPlot.enableAutoRange()

    def initTable(self):
        self.tableTH = EQTableWidget(spy.zeros((2048,4)))
        self.tableTH.setHeader(["Time","Acceleration","Velocity","Displacement"])
        self.tableSP = EQTableWidget(spy.zeros((2048,5)))
        self.tableSP.setHeader(["Period","SPA","SPV","SPD","SPE"])
        self.tableSPA = EQTableWidget(spy.zeros((2048,2)))
        self.tableSPA.setHeader(["Period","SPA"])

    def setDefaultValue(self):
        self.Freq1.setValue(round(1.0/(self.eqs.dt*self.eqs.n),3))
        self.Freq2.setValue(round(0.5/self.eqs.dt))
        self.TS.setValue(round(2.5*self.eqs.dt,3))
    
    def viewDataTH(self):
        # self.tableTH.setData(self.getTHData())
        # self.tableTH.setWindowTitle("Time Series Data")
        # self.tableTH.show()
        data = spy.vstack((self.eqs.t,self.eqs.acc,self.eqs.vel,self.eqs.disp)).T
        Data = BytesIO()
        spy.savetxt(Data,data,fmt="%12.6f",
            header="%12s\t%12s\t%12s\t%12s"%("Time","Acc",
                "Vel","Disp"),
            delimiter="\t")
        self.textEditTH.clear()
        self.textEditTH.setPlainText(Data.getvalue().decode()[2:])
        Data.close()
        self.textEditTH.show()

    def viewDataSP(self):
        # self.tableSP.setData(self.getSPData())
        # self.tableSP.show()
        i = self.CDR2.currentIndex()
        data = spy.vstack((self.eqs.sp[i].SPT,self.eqs.sp[i].SPA,self.eqs.sp[i].SPV,self.eqs.sp[i].SPD,self.eqs.sp[i].SPE)).T
        Data = BytesIO()
        spy.savetxt(Data,data,fmt="%12.6f",
            header="%12s\t%12s\t%12s\t%12s\t%12s"%("Period","SPA","SPV","SPD","SPE"),
            delimiter="\t")
        self.textBrowserSP.clear()
        self.textBrowserSP.setPlainText(Data.getvalue().decode()[2:])
        self.tabWidget.setCurrentIndex(4)
        Data.close()

    def viewDataSPA(self):
        # self.tableSPA.setData(self.getSPAData())
        
        i = self.CDR.currentIndex()

        data = spy.vstack((self.eqs.sp[i].SPT,self.eqs.sp[i].SPA)).T
        Data = BytesIO()
        spy.savetxt(Data,data,fmt="%14.8f",
            header="%14s\t%14s"%("Period","SPA"),
            delimiter="\t")
        self.textEditSPA.clear()
        self.textEditSPA.setPlainText(Data.getvalue().decode()[2:])
        self.textEditSPA.show()

        self.textEditSPA.setWindowTitle("zeta=%.2f"%self.eqs.sp[i].Zeta)
        # self.tableSPA.show()
        Data.close()

    def NormthenPlotTH(self):
        self.eqs.norm()
        self.plotTH()
    
    def updateCDR(self):
        self.CDR.clear()
        self.CDR2.clear()
        self.CDRfit.clear()
        DRs = self.DR.text().replace(" ","").split(",")
        self.CDR.addItems(DRs)
        self.CDRfit.addItems(DRs)
        DRs = ["Damping Ratio : "+dr for dr in DRs]
        self.CDR2.addItems(DRs)
    
    def openFile(self):

        fd = QtGui.QFileDialog()
        self.fileName = fd.getOpenFileName(self, "Open File", "./data/", "*.at2 *.txt")[0]
        self.URL.setText(self.fileName)
        self.reloadFile()

    def reloadFile(self):

        self.fileName = self.URL.text()

        if self.fileName[-4:] == ".txt":
            dt = QtGui.QInputDialog.getDouble(self, "Time Interval", "dt = ", value=0.02, decimals=3)[0]
            self.eqs.readTXTFile(self.fileName,dt)
            self.plotTH()
            self.tabWidget.setCurrentIndex(0)
            self.VDTH.setEnabled(True)

        elif self.fileName[-4:] == ".at2":
            self.eqs.readNGAFile(self.fileName)
            self.plotTH()
            self.tabWidget.setCurrentIndex(0)
            self.VDTH.setEnabled(True)
        else:
            pass

        self.setDefaultValue()

    def readNGAthenPlotTH(self):
        self.getNGAFileName()
        self.eqs.readNGAFile(self.fileName)
        self.plotTH()
        self.tabWidget.setCurrentIndex(0)
        self.VDTH.setEnabled(True)
        self.Freq1.setValue(round(1.0/(self.eqs.dt*self.eqs.n),2))
        self.Freq2.setValue(round(0.5/self.eqs.dt))
        self.TS.setValue(round(2.0*self.eqs.dt,2))

    def readTXTthenPlotTH(self):
        self.getTXTFileName()

        dt = QtGui.QInputDialog().getDouble(self, "Time Interval", "dt = ", value=0.02, decimals=3)[0]
        self.eqs.readTXTFile(self.fileName,dt)
        self.plotTH()
        self.tabWidget.setCurrentIndex(0)
        self.VDTH.setEnabled(True)

        self.Freq1.setValue(round(1.0/(self.eqs.dt*self.eqs.n),2))
        self.Freq2.setValue(round(0.5/self.eqs.dt))
        self.TS.setValue(round(2.0*self.eqs.dt,2))

    def getTrimIndice(self):
        thd1 = self.THD1.value()
        thd2 = self.THD2.value()

        iStart, iStop = self.eqs.getTrimIndice(thd1, thd2)
        self.iStart.setValue(iStart)
        self.iStop.setValue(iStop)

    def trimthenPlotTH(self):
        iStart = max(self.iStart.value()-1,0)
        iStop  = min(self.iStop.value()-1,self.eqs.n-1)
        self.eqs.trim(iStart,iStop)
        self.plotTH()

    def recoverthenPlotTH(self):
        self.eqs.recover()
        self.plotTH()

    def resetthenPlotTH(self):
        self.eqs.reset()
        self.plotTH()

    def adjustthenPlotTH(self):

        filt = self.Filt.isChecked()
        detr = self.Detrend.isChecked()
        tadj = self.TAdjust.isChecked()

        curr = False

        if filt:
            order = self.FOrder.value()
            f1 = self.Freq1.value()
            f2 = self.Freq2.value()
            btype = self.BandType.currentText()
            self.eqs.filt(order, f1, f2, btype, curr)
            curr = True

        if detr:
            oh = self.OHigh.value()
            ol = self.OLow.value()
            BLAM = self.DetrendMethod.currentText()

            if BLAM == "Detrend":
                self.eqs.detrendAcc(oh,ol,curr)
            elif BLAM == "Modified":
                self.eqs.baseLineCorr(oh,ol,curr)
            else:
                pass
            curr = True

        if tadj:
            ntp = self.NTP.value()
            TAM = self.TAMethod.currentText()

            if TAM == "Disp":
                self.eqs.targetDispCorr(ntp,curr)
            elif TAM == "DispVel":
                pass
            elif TAM == "DispVelAcc":
                pass
            else:
                pass
            curr = True

        if not curr:
            self.eqs.a2vd(curr)

        self.plotTH()

    def calSPthenPlotSP(self):
        self.getParaSP()
        self.eqs.getSpectra()
        self.plotSPA()
        self.tabWidget.setCurrentIndex(2)
        self.CDR.setEnabled(True)

    def calASPthenPlotASP(self):
        self.getParaSP()
        self.eqs.getAllSpectra()
        self.plotSP()
        self.tabWidget.setCurrentIndex(3)

    def clearLegend(self, legend):
        legend_label_texts = []
        for sample, label in legend.items:
            legend_label_texts.append(label.text)

        for text in legend_label_texts:
            legend.removeItem(text)

    def changeXS_FFT(self):
        X_LOG = self.X_LOG_FFT.isChecked()
        self.ViewFFT.getItem(0,0).setLogMode(x=X_LOG)

    def changeXS_SPA(self):
        X_LOG = self.X_LOG_SPA.isChecked()
        self.ViewSPA.getItem(0,0).setLogMode(x=X_LOG)

    def changeXS_SP(self):
        X_LOG = self.X_LOG_SP.isChecked()
        self.ViewSP.getItem(0,0).setLogMode(x=X_LOG)
        self.ViewSP.getItem(1,0).setLogMode(x=X_LOG)
        self.ViewSP.getItem(0,1).setLogMode(x=X_LOG)
        self.ViewSP.getItem(1,1).setLogMode(x=X_LOG)

    def plotTH(self):
        kpo = self.RawON.isChecked()
        self.ViewTH.clear()
        self.initViewTH()
        accItem = self.ViewTH.getItem(0,0)
        if kpo: accItem.plot(self.eqs.t,self.eqs.acc_raw,pen=0.5,name="Original")
        accItem.plot(self.eqs.t,self.eqs.acc,pen="b",name="Adjusted")

        velItem = self.ViewTH.getItem(1,0)
        if kpo: velItem.plot(self.eqs.t,self.eqs.vel_raw,pen=0.5,name="Original")
        velItem.plot(self.eqs.t,self.eqs.vel,pen="b",name="Adjusted")

        dispItem = self.ViewTH.getItem(2,0)
        if kpo: dispItem.plot(self.eqs.t,self.eqs.disp_raw,pen=0.5,name="Original")
        dispItem.plot(self.eqs.t,self.eqs.disp,pen="b",name="Adjusted")

        acc_peak_loc   = abs(self.eqs.acc).argmax()
        acc_peak_time  = acc_peak_loc*self.eqs.dt
        acc_peak_value = self.eqs.acc[acc_peak_loc]
        self.statusBar().showMessage("Peak Value of Acceleration is %.3f at t = %.3f s"%(acc_peak_value, acc_peak_time))
        # self.plotFFT()

    def FFTPSD(self):
        i = self.FSP.currentIndex()
        if i == 0:
            self.plotFFT()
        elif i == 1:
            self.plotPSD()
        else:
            pass

    def plotFFT(self):
        self.eqs.fft()
        FFTItem = self.ViewFFT.getItem(0,0)
        FFTItem.clear()
        FFTItem.setTitle("Fourier Amplitude Spectrum")
        FFTItem.setLabels(left="Fourier Amplitude",bottom="Frequency (Hz)")
        n = len(self.eqs.freq)/2
        FFTItem.plot(self.eqs.freq[1:n], 2.0*abs(self.eqs.accf[1:n]), pen="b")

    def plotPSD(self):
        self.eqs.psd()
        FFTItem = self.ViewFFT.getItem(0,0)
        FFTItem.clear()
        FFTItem.setTitle("Power Spectral Density (Welch's method)")
        FFTItem.setLabels(left="PSD",bottom="Frequency (Hz)")
        n = len(self.eqs.freq)/2
        FFTItem.plot(self.eqs.freq[1:n], 2.0*abs(self.eqs.accf[1:n]), pen="b")

    def plotSPA(self):
        self.ViewSPA.clear()
        self.initViewSPA()
        SPItem = self.ViewSPA.getItem(0,0)
        SPItem.legend.show()
        if self.DM.currentText() == "linear":
            SPItem.setLogMode(x=False)
            self.X_LIN_SPA.setChecked(True)
            self.X_LOG_SPA.setChecked(False)
        elif self.DM.currentText() == "log":
            SPItem.setLogMode(x=True)
            self.X_LIN_SPA.setChecked(False)
            self.X_LOG_SPA.setChecked(True)

        cl = AutoPen()

        for sp in self.eqs.sp:
            SPItem.plot(sp.SPT,sp.SPA,pen=cl.next(),name="&zeta; = %.2f"%sp.Zeta)
            if self.SPATON.isChecked():
                SPItem.plot(sp.SPT,sp.SPAT,pen=pg.mkPen(cl.color,width=2,dash=[5,3]))
            if self.SPAPON.isChecked():
                SPItem.plot(sp.SPT,sp.SPA_bak,pen=pg.mkPen(0.5,width=2))

    def plotCurrentSPA(self):
        i = self.CDRfit.currentIndex()
        self.plotiSPA(i)

    def plotiSPA(self,i):
        self.ViewSPA.clear()
        self.initViewSPA()
        SPItem = self.ViewSPA.getItem(0,0)
        SPItem.legend.show()
        SPItem.setLogMode(x=self.X_LOG_SPA.isChecked())

        pen = pg.mkPen("b",width=2)
        penT = pg.mkPen("r",width=2)
        sp = self.eqs.sp[i]
        if self.SPAPON.isChecked():
            SPItem.plot(sp.SPT,sp.SPA_bak,pen=pg.mkPen(0.5,width=2),name="Pre-Fitted")
        if self.SPATON.isChecked():
            SPItem.plot(sp.SPT,sp.SPAT,pen=penT,name="Code Spectrum")
        SPItem.plot(sp.SPT,sp.SPA,pen=pen,name="Fitted")

    def plotSP(self):
        PenA = AutoPen()
        PenV = AutoPen()
        PenD = AutoPen()
        PenE = AutoPen()

        self.ViewSP.clear()
        self.initViewSP()
        SPAItem = self.ViewSP.getItem(0,0)
        SPAItem.legend.show()
        if self.DM.currentText() == "linear":
            SPAItem.setLogMode(x=False)
            self.X_LIN_SP.setChecked(True)
            self.X_LOG_SP.setChecked(False)
        elif self.DM.currentText() == "log":
            SPAItem.setLogMode(x=True)
            self.X_LIN_SP.setChecked(False)
            self.X_LOG_SP.setChecked(True)

        SPVItem = self.ViewSP.getItem(0,1)
        SPVItem.legend.show()
        if self.DM.currentText() == "linear":
            SPVItem.setLogMode(x=False)
        elif self.DM.currentText() == "log":
            SPVItem.setLogMode(x=True)

        SPDItem = self.ViewSP.getItem(1,0)
        SPDItem.legend.show()
        if self.DM.currentText() == "linear":
            SPDItem.setLogMode(x=False)
        elif self.DM.currentText() == "log":
            SPDItem.setLogMode(x=True)

        SPEItem = self.ViewSP.getItem(1,1)
        SPEItem.legend.show()
        if self.DM.currentText() == "linear":
            SPEItem.setLogMode(x=False)
        elif self.DM.currentText() == "log":
            SPEItem.setLogMode(x=True)

        for sp in self.eqs.sp:
            SPAItem.plot(sp.SPT,sp.SPA,pen=PenA.next(),name="&zeta; = %.2f"%sp.Zeta)
            SPVItem.plot(sp.SPT,sp.SPV,pen=PenV.next(),name="&zeta; = %.2f"%sp.Zeta)
            SPDItem.plot(sp.SPT,sp.SPD,pen=PenD.next(),name="&zeta; = %.2f"%sp.Zeta)
            SPEItem.plot(sp.SPT,sp.SPE,pen=PenE.next(),name="&zeta; = %.2f"%sp.Zeta)

    def getTXTFileName(self):
        fd = QtGui.QFileDialog()
        self.fileName = fd.getOpenFileName(self, "file", "./data/", "*.txt", "Plain Text File (*.txt *.TXT)")[0]

    def getNGAFileName(self):
        fd = QtGui.QFileDialog()
        self.fileName = fd.getOpenFileName(self, "file", "./data/", "*.at2", "PEER Record File (*.at2 *.AT2)")[0]

    def getParaSP(self):
        Zeta = [float(zi) for zi in self.DR.text().split(",")]
        Tstart = self.TS.value()
        Tstop  = self.TL.value()
        NP = self.NP.value()
        DM = self.DM.currentText()
        SM = self.SM.currentText()
        PD = self.PD.isChecked()
        Tg = self.Tg.value()
        self.eqs.setupSpectra(NP,Tstart,Tstop,DM,Zeta,SM,PD)
        for sp in self.eqs.sp:
            sp.getCodeSpectra(Tg)

    def fitSpectra(self):
        self.getParaSP()
        self.eqs.getSpectra()
        self.eqs.backupSpectra()
        i = self.CDRfit.currentIndex()
        m = self.FitMethod.currentIndex()
        tol = self.Tol.value()
        mit = self.MIT.value()
        
        self.eqs.fitSpectra(i,tol,mit,m)
        self.eqs.getSpectra()
        aer,mer = self.eqs.sp[i].getError()
        self.statusBar().showMessage("Spectral Fitting Finished: Mean Error: %.3f%% \t Max Error: %.3f%%"%(aer*100,mer*100))
        self.plotiSPA(i)

    # def getTHData(self):
    #     Data = spy.vstack((self.eqs.t,self.eqs.acc,self.eqs.vel,self.eqs.disp)).T
    #     return Data

    # def getSPData(self):
    #     i = self.CDR.currentIndex()
    #     Data = spy.vstack((self.eqs.sp[i].SPT,self.eqs.sp[i].SPA,self.eqs.sp[i].SPV,self.eqs.sp[i].SPD,self.eqs.sp[i].SPE)).T
    #     return Data

    # def getSPAData(self):
    #     i = self.CDR.currentIndex()
    #     Data = spy.vstack((self.eqs.sp[i].SPT,self.eqs.sp[i].SPA)).T
    #     return Data